package com.ren.scale.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName: ThreadPoolConfig
 * @Description: TODO
 * @Author: RZY
 * @DATE: 2022/7/19 10:56
 * @Version: v1.0
 */

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    //核心线程数
    @Value("${ThreadPool.corePoolSize}")
    private int corePoolSize;

    //最大线程数
    @Value("${ThreadPool.maxPoolSize}")
    private int maxPoolSize;

    //工作线程活跃时间
    @Value("${ThreadPool.keepAliveTime}")
    private int keepAliveTime;

    //阻塞队列容量
    @Value("${ThreadPool.BlockingQueueCapacity}")
    private int BlockingQueueCapacity;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(ThreadFactory threadFactory) {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(corePoolSize);
        threadPool.setMaxPoolSize(maxPoolSize);
        threadPool.setKeepAliveSeconds(keepAliveTime);
        threadPool.setQueueCapacity(BlockingQueueCapacity);
        threadPool.setThreadFactory(threadFactory);
        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy：由调用线程（提交任务的线程）处理该任务
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        threadPool.initialize();
        return threadPool;
    }

    @Bean
    public ThreadFactory threadFactory() {
        //自定义线程工厂
        return new ThreadFactoryBuilder().setNameFormat("recl-pool-").build();
    }
}
